package com.pp.tourism.web.controller;

import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Api(description = "页面跳转")
@RestController
public class IndexController {

    @RequestMapping(value = "/login")
    public ModelAndView login(){
        ModelAndView modelAndView = new ModelAndView("web/login");
        return modelAndView;
    }
    @RequestMapping(value = "/show")
    public ModelAndView show() {
        ModelAndView modelAndView = new ModelAndView("web/show");
        return modelAndView;
    }
    @RequestMapping(value = "/admin")
    public ModelAndView admin(){
        ModelAndView modelAndView = new ModelAndView("web/admin");
        return modelAndView;
    }

    //多文件上传
    @RequestMapping(value ="/upload",method = RequestMethod.POST)
    @ResponseBody
    public List<String> upload(@RequestParam(value = "files",required = false) MultipartFile[] file, HttpServletRequest request) throws Exception{
        /*System.out.println(file.length);*/
        //写出路径
        String path= request.getSession().getServletContext().getRealPath("images/");
        List<String> pathForView = new ArrayList<String>();
        // String path="/home/tomcat/webapps/tourism/images";
        for(int i=0;i<file.length;i++){
            //获取文件名
            String name = file[i].getOriginalFilename();
            //获取文件源
            InputStream ips = file[i].getInputStream();
            //写出
            FileOutputStream fileOutputStream = new FileOutputStream(path+name);
            int index;
            byte[] bytes = new byte[1024];
            while ((index = ips.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, index);
                fileOutputStream.flush();
            }
            fileOutputStream.close();
            /*System.out.println("name:"+name+"\n"+"ips:"+ips);*/
            pathForView.add(name);
        }
        return pathForView ;
    }
}
